import { Component, OnInit, HostBinding, Output, EventEmitter, Input, TemplateRef, ElementRef } from '@angular/core';

import { MenuStateService, MenuRouterHandlerType } from './menu-state.service';

export type MenuMode = 'foldable' | 'float';

@Component({
  selector: 'fui-menu',
  templateUrl: './menu.component.html',
  providers: [ MenuStateService ],
})
export class MenuComponent implements OnInit {
  @HostBinding('class.fui-menu') hostClass = true;

  @HostBinding('class.collapsed') collapsed = false;

  /** Preset seleted key. */
  @Input() selectedKey: string;

  /** Set to true to use route handler. Otherwize use normal handler. */
  @Input() set routeHandler(value: boolean) {
    if (value === false) {
      this.handlerType = 'normal';
    } else {
      this.handlerType = 'route';
    }
  }

  /** Set initial collapse state. */
  @Input() initCollapse = false;

  /** Menu mode, support 'foldable' and 'float'. */
  @Input() mode: MenuMode = 'float';

  /** Menu title. */
  @Input() menuTitle: string;

  /** Optional menu head template. */
  @Input() menuHeadTemplate: TemplateRef<{$implicit: boolean; collapsed: boolean}>;

  /** Optional menu template. */
  @Input() menuTemplate: TemplateRef<{$implicit: boolean; collapsed: boolean}>;

  /** Emit collapse state. */
  @Output() collapsedChange = new EventEmitter();

  /** Emit selection change. */
  @Output() selectChange = new EventEmitter();

  handlerType: MenuRouterHandlerType;

  get context() {
    return {
      $implicit: this.collapsed,
      collapsed: this.collapsed,
    };
  }

  constructor(
    private state: MenuStateService,
    public elementRef: ElementRef,
  ) { }

  ngOnInit() {
    this.collapsed = this.initCollapse;

    this.state.selectedKeyObservable.subscribe((selectedKey) => {
      if (selectedKey !== this.selectedKey) {
        this.selectChange.emit(selectedKey);
      }
    });
    setTimeout(() => {
      this.state.init(this.handlerType, this.selectedKey);
    });
  }

  toggle() {
    this.collapsed = !this.collapsed;
    this.collapsedChange.emit(this.collapsed);
  }
}
